<template>
  <div class='login'>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="login-ruleForm">
        <el-form-item label="用户名" prop="username">
            <el-input v-model="ruleForm.username" placeholder="请输入用户名：admin"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input v-model="ruleForm.password" show-password placeholder="初始密码123123"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button class="login-btn"  type="primary" @click="submitForm('ruleForm')">登录</el-button>
        </el-form-item>
        </el-form>
  </div>
</template>

<script>
import axios from 'axios'
import {mapMutations} from "vuex"
export default {
  name: 'login',
  data(){
    return {
        ruleForm: {
          username: '',
          password: ''
        },
        rules: {
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 16, message: '长度在 3 到 16 个字符', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'change' },
            { min: 3, max: 16, message: '长度在 3 到 16 个字符', trigger: 'blur' }
          ],
        }
    }
  },
  methods: {
    submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.login()

          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      login(){
            axios.post("http://localhost:3000/api/userlogin",this.ruleForm)
            .then((result) => {
                if(result.data.code === 200){
                    this.SET_USER_INFO(result.data.list)
                    // 跳转到首页
                    this.$router.push("/")
                }

            }).catch((err) => {
                console.log(err)
            });
      },
      ...mapMutations(["SET_USER_INFO"])
  }
}
</script>
<style scoped lang="scss">
.login-ruleForm{
    width:400px;
    margin:100px auto;
}
.login-btn{
    width:100%;
}
</style>
